package com.oren.util;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;


/**
 * Created by IntelliJ IDEA.
 * User: wangshiwei
 * Date: 2018/6/13
 * Time: 16:42
 * describe: 数据库操作工具类
 */
public final class DatabaseUtil {

    private static final Logger LOGGER= LoggerFactory.getLogger(DatabaseUtil.class);

    private static final QueryRunner QUERY_RUNNER;

    //创建线程对象
    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL;

    //利用dpcp2的对象去操作数据库
    private static final BasicDataSource DATA_SOURCE;



/*    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;*/

    //静态代码块 在这个类加载后 就会执行这个静态代码块
    static {
        System.out.printf("静态代码块开始执行======");
        CONNECTION_THREAD_LOCAL=new ThreadLocal<Connection>();

        QUERY_RUNNER=new QueryRunner();

        Properties properties=PropertiesUtil.loadPros("config.properties");
        String driver=PropertiesUtil.getString(properties,"jdbc.driver");
        String  url=PropertiesUtil.getString(properties,"jdbc.url");
        String username=PropertiesUtil.getString(properties,"jdbc.username");
        String    password=PropertiesUtil.getString(properties,"jdbc.password");

        DATA_SOURCE=new BasicDataSource();
        DATA_SOURCE.setDriverClassName(driver);
        DATA_SOURCE.setUrl(url);
        DATA_SOURCE.setUsername(username);
        DATA_SOURCE.setPassword(password);
        System.out.printf("静态代码块执行完成======");
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection(){
        /*Connection connection=null;
        try {
            connection= DriverManager.getConnection(URL,USERNAME,PASSWORD);
        }catch (SQLException e){
            LOGGER.error("get connection failure",e);
        }
        return connection;*/
        Connection connection=CONNECTION_THREAD_LOCAL.get();
        if(connection==null){
            try {
                connection=DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                LOGGER.error("get connection failure",e);
                throw new RuntimeException(e);
            }finally {
                CONNECTION_THREAD_LOCAL.set(connection);
            }
        }
        return connection;

    }

    /**
     * 关闭数据库连接(用了连接池之后 就不需要这个关闭的方法，一般连接池会自动去管理这些东西)
     * @param connection
     */
    public static void closeConnection(Connection connection){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.error("close connection failure");
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据相关参数查询数据，并返回实体类
     * @param entity
     * @param sql 传入的sql语句
     * @param params 传入的参数
     * @param <T>
     * @return 返回list集合的实体类
     */
    /*public static <T> List<T> queryEntity(Class<T> entity, String sql, Object... params){
        List<T> entityList;
        Connection connection=getConnection();
        try {
            LOGGER.debug("数据库操作开始~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            LOGGER.debug("输入参数为："+params);
            entityList=QUERY_RUNNER.query(connection,sql,new BeanListHandler<T>(entity),params);
            LOGGER.debug("返回的数据长度为："+entityList.size());
            LOGGER.debug("返回的数据为（取前10条）");
            for (T t:entityList) {
                LOGGER.debug(t.toString());
            }
        } catch (SQLException e) {
            LOGGER.error("query entity list failure",e);
            throw new RuntimeException(e);
        }
        LOGGER.debug("数据库操作结束~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        return entityList;

    }*/


}
